#include"touch.h"

/*-----触摸屏的初始化-----*/
void touchscreen_init(TouchScreen *ts)
{
    //打开触摸屏
    ts->fd = open("/dev/input/event0",O_RDWR);
    if(ts->fd < 0 )
    {
        perror("open touchscreen fail");
        return ;
    }

    //获取X,Y轴的最大值
    if(ioctl(ts->fd,EVIOCGABS(ABS_X),&ts->abs_x) == -1)
    {
        perror("获取x轴参数失败");
        close(ts->fd);
        return;
    }
    if(ioctl(ts->fd,EVIOCGABS(ABS_Y),&ts->abs_y) == -1)
    {
        perror("获取y轴参数失败");
        close(ts->fd);
        return;
    }

}

/*-----触摸屏的反初始化-----*/
void touchscreen_uninit(TouchScreen *ts)
{
    close(ts->fd);
}

/*---按下响应(获取x和y的值,立即返回)---*/
void ts_press(Coordinate *coor,TouchScreen *ts)
{
    //定义输入事件结构体
    struct input_event buf;
    coor->x = -1,coor->y = -1;
    while(1)
    {
        bzero(&buf,sizeof(buf));
        read(ts->fd,&buf,sizeof(buf));

        //绝对事件(触摸屏)
        if(buf.type == EV_ABS && buf.code == ABS_X)
            coor->x = buf.value * 800/ts->abs_x.maximum;

        if(buf.type == EV_ABS && buf.code == ABS_Y)
            coor->y = buf.value * 480/ts->abs_y.maximum;
        
        if(coor ->x != -1 && coor->y != -1)
            break;
    }
}

/*-----松开响应(离开屏幕，返回)----*/
void ts_loosen(Coordinate *coor,TouchScreen *ts)
{
    //定义输入事件结构体
    struct input_event buf;
    coor->x =-1,coor->y =-1;
    while(1)
    {
        bzero(&buf,sizeof(buf));
        read(ts->fd,&buf,sizeof(buf));

        //按键事件
        if(buf.type == EV_KEY && buf.code == BTN_TOUCH)
        {
            if(buf.value == 0)
            {
                break;
            }
        }

        //绝对事件(触摸屏)
        if(buf.type == EV_ABS && buf.code == ABS_X)
            coor->x = buf.value * 800 /ts->abs_x.maximum;
        
        if(buf.type == EV_ABS && buf.code == ABS_Y)
            coor->y = buf.value * 480 /ts->abs_y.maximum;
    }
}


/*---------滑屏------------*/
void ts_slide_screen(Coordinate *coor,TouchScreen *ts)
{
    Coordinate start,stop;
    ts_press(&start,ts);
    ts_loosen(&stop,ts);

    int xx = stop.x - start.x;
    int yy = stop.y - start.y;

    //存储离开时的坐标
    coor->x = stop.x;
    coor->y = stop.y;

    //在这个区域产生偏差为点击
    if(xx*xx + yy*yy <40*40)
        coor->action =CLICK;
    
    //左滑或右滑
    coor->action = xx > 0 ? SLIDE_RIGHT : SLIDE_LEFT;
    coor->action = yy > 0 ? SLIDE_DOWN : SLIDE_UP;
}
